#!/usr/bin/env python

__doc__ = """
tagAppend
=========

:Authors: Karl Norby
:Version: 1.0
:Date: Sept. 5th, 2007

Deletes all tags found that matches a given XPath expression in an xml file.

Arguments
---------

1. tagname
2. append string
3. *optional* filename (from stdin)
4. *optional* output (goes to stdout by default)

"""

import lxml.etree as ET
import os, sys

def tagAppend(tagname, appendString, xmlInput, xmlOutput=None):
    finder = ET.XPath("//" + tagname)
    tree   = ET.parse(xmlInput)
    root   = tree.getroot()
    res    = finder(root)
    [elem.append(ET.XML(appendString)) for elem in res]
    retval = ET.tostring(tree, pretty_print=True)
    if xmlOutput==None:
        return retval
    print >> xmlOutput, retval

def main():
    argc = len(sys.argv)
    if argc<3 or argc>5:
        raise "error: Wrong number of arguments"
    expr = sys.argv[1]

    appendString = sys.argv[2]
    
    if argc==4 or argc==5:
        filename = sys.argv[3]
        if not os.path.isfile(filename):
            raise IOError, "%s is not a file" % filename
    else:
        filename = sys.stdin
    
    if argc==5:
        output = sys.argv[4]
        output = open(output, "w")
    else:
        output = sys.stdout

    tagAppend(expr, appendString, filename, output)
    sys.exit(0)

if __name__=="__main__":
    main()
